package com.yxzx.ebs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxzx.common.EduException;
import com.yxzx.ebs.entity.EbsSubject;
import com.yxzx.ebs.entity.vo.EbsSubjectNestedVo;
import com.yxzx.ebs.entity.vo.EbsSubjectVo;
import com.yxzx.ebs.mapper.EbsSubjectMapper;
import com.yxzx.ebs.service.EbsSubjectService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author kongfuzi
 * @since 2020-07-29
 */
@Service
public class EbsSubjectServiceImpl extends ServiceImpl<EbsSubjectMapper, EbsSubject> implements EbsSubjectService {

    //读取excel内容添加到分类表
    @Override
    public List<String> importSubject(MultipartFile file) {
        List<String> msg = new ArrayList<>();//存储错误信息
        try {
            //1.获取文件输入流
            InputStream inputStream = file.getInputStream();
            //2.创建workbook
            Workbook workbook = new XSSFWorkbook(inputStream);
            //3.根据workbook获取sheet
            Sheet sheet = workbook.getSheetAt(0);
            //4.根据sheet获取row,循环遍历获取行
            int lastRowNum = sheet.getLastRowNum();
            //第一行是标题不读取
            for (int i = 1; i <= lastRowNum; i++) {
                Row row = sheet.getRow(i);
                if (row == null){
                    String str = "第"+i+"行数据为空";
                    msg.add(str);
                    continue;
                }
                //5.根据row获取列
                Cell cellOne = row.getCell(0);
                if (cellOne == null){
                    String str = "第"+i+"行第一列为空";
                    msg.add(str);
                    continue;
                }
                String cellOneValue = cellOne.getStringCellValue();
                //添加一级分类,因为excel里面有很多重复的一级分类
                //在添加之前进行判断，如果一级分类存在数据库表里，就不添加
                EbsSubject existOneSubject = this.existOneSubject(cellOneValue);
                String parentId = null;
                if( existOneSubject == null ){ //不存在添加
                    EbsSubject ebsSubject = new EbsSubject();
                    ebsSubject.setTitle(cellOneValue);
                    ebsSubject.setParentId("0");
                    ebsSubject.setSort(0);
                    baseMapper.insert(ebsSubject);
                    //把新添加的ID赋值给parentId
                    parentId = ebsSubject.getId();
                } else {  //存在不添加
                    //把一级分类ID赋值给parentId
                    parentId = existOneSubject.getId();
                }

                //获取第二列
                //判断二级分类是否存在
                Cell cellTwo = row.getCell(1);
                if (cellTwo == null){
                    String str = "第"+i+"行第二列为空";
                    msg.add(str);
                    continue;
                }
                String cellTwoValue = cellTwo.getStringCellValue();
                EbsSubject ebsSubjectTwo = this.existTwoSubject(cellTwoValue, parentId);
                if (ebsSubjectTwo == null){
                    EbsSubject ebsSubject = new EbsSubject();
                    ebsSubject.setTitle(cellTwoValue);
                    ebsSubject.setParentId(parentId);
                    ebsSubject.setSort(0);
                    baseMapper.insert(ebsSubject);
                }
            }
            return msg;
        }catch (Exception e){
            e.printStackTrace();
            throw new EduException(20001,"分类导入失败，出现异常:"+e.getMessage());
        }

    }

    /**
     * 嵌套树形结构列表数据
     * @return
     */
    @Override
    public List<EbsSubjectNestedVo> nestedList() {
        //最终获取的数据列表
        List<EbsSubjectNestedVo> subjectNestedVoList = new ArrayList<>();

        //获取一级分类数据记录
        QueryWrapper<EbsSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",0);
        queryWrapper.orderByAsc("sort","id");
        List<EbsSubject> subjects = super.list(queryWrapper);

        //填充一级分类vo数据
        for (int i=0,count=subjects.size(); i<count; i++){
            EbsSubject ebsSubject = subjects.get(i);
            //创建一级分类vo对象
            EbsSubjectNestedVo subjectNestedVo = new EbsSubjectNestedVo();
            BeanUtils.copyProperties(ebsSubject,subjectNestedVo);

            //获取二级分类数据记录
            List<EbsSubjectVo> subjectVos2 = new ArrayList<>();
            QueryWrapper<EbsSubject> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("parent_id",ebsSubject.getId());
            queryWrapper2.orderByDesc("sort","id");
            List<EbsSubject> ebsSubjects2 = super.list(queryWrapper2);
            //使用stream拷贝list
            List<EbsSubjectVo> ebsSubjectVos = ebsSubjects2.stream().map(e -> {
                EbsSubjectVo vo = new EbsSubjectVo();
                BeanUtils.copyProperties(e, vo);
                return vo;
            }).collect(Collectors.toList());

            //封装到subjectNestedVo
            subjectNestedVo.setChildren(ebsSubjectVos);
            //放到最终的集合中
            subjectNestedVoList.add(subjectNestedVo);
        }
        //返回最终数据
        return subjectNestedVoList;
    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    @Override
    public boolean deleteSubjectById(String id) {
        //判断一级分类下面有没有二级分类，根据parent_id查询
        QueryWrapper<EbsSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        //判断如果有有二级分类
        if (count > 0){
            return false;
        }else{
            return baseMapper.deleteById(id) > 0;//执行删除
        }
    }

    /**
     * 添加一级分类
     * @param subject
     * @return
     */
    @Override
    public boolean saveLevelOne(EbsSubject subject) {
        EbsSubject ebsSubject = this.existOneSubject(subject.getTitle());
        if (ebsSubject == null){
            subject.setParentId("0");
            return this.save(subject);
        }
        return false;
    }

    /**
     * 添加二级分类
     * @param subject
     * @return
     */
    @Override
    public boolean saveLevelTwo(EbsSubject subject) {
        //判断二级分类是否存在
        EbsSubject existTwoSubject = this.existTwoSubject(subject.getTitle(), subject.getParentId());
        if (existTwoSubject == null){
            int insert = baseMapper.insert(subject);
            return insert > 0;
        }
        return false;
    }

    //判断数据库表里是否存在二级分类
    private EbsSubject existTwoSubject(String title,String parentId){
        QueryWrapper<EbsSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",title).eq("parent_id",parentId);
        EbsSubject ebsSubject = baseMapper.selectOne(wrapper);
        return ebsSubject;
    }
    //判断数据库表里是否存在一级分类
    private EbsSubject existOneSubject(String title){
        QueryWrapper<EbsSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id","0");
        EbsSubject ebsSubject = baseMapper.selectOne(queryWrapper);
        return ebsSubject ;
    }
}
